package com.example.democonfigserver.modules.config;

import com.example.democonfigserver.modules.app.App;
import com.example.democonfigserver.modules.app.AppRepository;
import com.example.democonfigserver.modules.env.Env;
import com.example.democonfigserver.modules.env.EnvRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;

import static com.example.democonfigserver.constant.ValidationConstant.ERROR_MESSAGE_ENV_ID_NULL;
import static com.example.democonfigserver.constant.ValidationConstant.ERROR_MESSAGE_PROJECT_ID_NULL;

/**
 * @author wangbin
 */
@RestController
@RequestMapping("/conf")
@Validated
public class ConfigController {
    @Resource
    private ConfigRepository configRepository;
    @Resource
    private EnvRepository envRepository;
    @Resource
    private AppRepository appRepository;

    @GetMapping
    public Page<Config> pageList(Pageable pageable, @NotNull(message = ERROR_MESSAGE_ENV_ID_NULL) Integer envId) {
        return configRepository.findPageByEnvId(pageable, envId);
    }

    @GetMapping("/findAll")
    public List<Config> findAll(@NotNull(message = ERROR_MESSAGE_PROJECT_ID_NULL) Integer envId) {
        return configRepository.findAllByEnvId(envId);
    }

    @GetMapping("/{id}")
    public Config getOne(@PathVariable Integer id) {
        return configRepository.findByIdFetchProperty(id);
    }

    @PostMapping
    public void save(@RequestBody @Valid Config config, @NotNull(message = ERROR_MESSAGE_ENV_ID_NULL) Integer envId) {
        if (config.getEnv() == null) {
            Env env = envRepository.findById(envId).orElseThrow(NullPointerException::new);
            config.setEnv(env);
        }
        configRepository.save(config);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Integer id) {
        List<App> appList = appRepository.findFetchConfigByConfigId(Collections.singletonList(id));
        appList.forEach(a -> a.getConfigList().removeIf(c -> c.getId().equals(id)));
        appRepository.saveAll(appList);
        configRepository.deleteById(id);
    }
}
